import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress' // 顶部进度条
import statistics from './statistics' // 统计
import * as LoginAction from '@/utils/login'

import routes from './routes'

NProgress.configure({ showSpinner: false }) // 配置进度条，去除进度条loading

Vue.use(Router)

const router = new Router({
  // base: '',
  mode: 'history', // require service support (另外支持hash)
  scrollBehavior: (to, from, savedPosition) => savedPosition || { x: 0, y: 0 },
  routes
})

// 路由声明周期
router.beforeEach(async (to, from, next) => {
  NProgress.start() // 顶部进度条开始
  // 登陆
  const { needLogin } = to.meta || {}
  if (needLogin || to.query.code) {
    const { name, query, params } = to
    delete params.code
    const { href } = router.resolve({ name, query, params })
    const back = window.location.origin + href
    await LoginAction.login(back)
  }
  next()
})

router.afterEach(route => {
  // 设置路由title
  if (route.meta.title) {
    document.title = route.meta.title || '卢忠宽'
  }

  // 拿到正确的路径，多以添加延迟
  setTimeout(() => {
    statistics({ route, router }) // 百度统计
  }, 300)

  NProgress.done()
})

export default router
